package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.merchant.domain.Category;
import com.ruoyi.merchant.mapper.CategoryMapper;
import com.ruoyi.merchant.service.ICategoryService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分类Service业务层处理
 */
@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category selectCategoryByCategoryId(Long categoryId) {
        Category category = categoryMapper.selectCategoryByCategoryId(categoryId);
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (category != null && !merchantId.equals(category.getMerchantId())) {
            throw new ServiceException("无权访问该分类");
        }
        return category;
    }

    @Override
    public List<Category> selectCategoryList(Category category) {
        category.setMerchantId(MerchantSecurityUtils.getMerchantId());
        return categoryMapper.selectCategoryList(category);
    }

    @Override
    public List<Category> buildCategoryTree(List<Category> categories) {
        List<Category> returnList = new ArrayList<>();
        List<Long> tempList = categories.stream()
                .map(Category::getCategoryId)
                .collect(Collectors.toList());

        for (Category category : categories) {
            // 如果是顶级节点，或者父节点不在列表中，则认为是根节点
            if (category.getParentId() == null ||
                    category.getParentId() == 0 ||
                    !tempList.contains(category.getParentId())) {
                recursionFn(categories, category);
                returnList.add(category);
            }
        }
        if (returnList.isEmpty()) {
            returnList = categories;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Category> list, Category t) {
        // 得到子节点列表
        List<Category> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Category tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Category> getChildList(List<Category> list, Category t) {
        List<Category> tlist = new ArrayList<>();
        Iterator<Category> it = list.iterator();
        while (it.hasNext()) {
            Category n = it.next();
            if (n.getParentId() != null &&
                    n.getParentId().longValue() == t.getCategoryId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Category> list, Category t) {
        return getChildList(list, t).size() > 0;
    }

    @Override
    @Transactional
    public int insertCategory(Category category) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        category.setMerchantId(merchantId);

        // **关键修复：验证父分类是否属于当前商家**
        if (category.getParentId() != null && category.getParentId() != 0) {
            Category parentCategory = categoryMapper.selectCategoryByCategoryId(category.getParentId());
            if (parentCategory == null) {
                throw new ServiceException("父分类不存在");
            }
            if (!merchantId.equals(parentCategory.getMerchantId())) {
                throw new ServiceException("无权在该分类下创建子分类");
            }
        }

        // 校验分类名称唯一性
        if (UserConstants.NOT_UNIQUE == checkCategoryNameUnique(category)) {
            throw new ServiceException("分类名称已存在");
        }

        return categoryMapper.insertCategory(category);
    }

    @Override
    @Transactional
    public int updateCategory(Category category) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        category.setMerchantId(merchantId);

        // 验证分类是否存在且属于当前商家
        Category existCategory = categoryMapper.selectCategoryByCategoryId(category.getCategoryId());
        if (existCategory == null) {
            throw new ServiceException("分类不存在");
        }
        if (!merchantId.equals(existCategory.getMerchantId())) {
            throw new ServiceException("无权修改该分类");
        }

        // **关键修复：验证新的父分类是否属于当前商家**
        if (category.getParentId() != null && category.getParentId() != 0) {
            Category parentCategory = categoryMapper.selectCategoryByCategoryId(category.getParentId());
            if (parentCategory == null) {
                throw new ServiceException("父分类不存在");
            }
            if (!merchantId.equals(parentCategory.getMerchantId())) {
                throw new ServiceException("无权移动到该分类下");
            }
        }

        // 校验分类名称唯一性
        if (UserConstants.NOT_UNIQUE == checkCategoryNameUnique(category)) {
            throw new ServiceException("分类名称已存在");
        }

        return categoryMapper.updateCategory(category);
    }

    @Override
    @Transactional
    public int deleteCategoryByCategoryIds(Long[] categoryIds) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        for (Long categoryId : categoryIds) {
            Category category = categoryMapper.selectCategoryByCategoryId(categoryId);
            if (category == null || !merchantId.equals(category.getMerchantId())) {
                throw new ServiceException("包含无权删除的分类");
            }

            // 检查是否有子分类
            if (categoryMapper.selectChildrenCount(categoryId, merchantId) > 0) {
                throw new ServiceException("存在子分类，不允许删除");
            }

            // 检查该分类下是否有商品
            if (categoryMapper.selectProductCountByCategoryId(categoryId) > 0) {
                throw new ServiceException("分类下存在商品，不允许删除");
            }
        }
        return categoryMapper.deleteCategoryByCategoryIds(categoryIds);
    }

    @Override
    @Transactional
    public int deleteCategoryByCategoryId(Long categoryId) {
        return deleteCategoryByCategoryIds(new Long[]{categoryId});
    }

    @Override
    public boolean checkCategoryNameUnique(Category category) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        Long categoryId = category.getCategoryId() == null ? -1L : category.getCategoryId();
        Category info = categoryMapper.checkCategoryNameUnique(
                category.getName(),
                merchantId,
                category.getParentId()
        );
        if (StringUtils.isNotNull(info) && info.getCategoryId().longValue() != categoryId.longValue()) {
            return UserConstants.NOT_UNIQUE;  // 返回 false，表示不唯一
        }
        return UserConstants.UNIQUE;  // 返回 true，表示唯一
    }
}
